using Minio;
using Minio.DataModel.Args;
using System;
using System.IO;
using System.Net.Mime;
using System.Threading;
using System.Threading.Tasks;

namespace RBAC.Write.Api.Infrastructure.Storage
{
    public class MinioObjectStorage : IObjectStorage
    {
        private readonly IMinioClient _client;

        public MinioObjectStorage(IMinioClient client)
        {
            _client = client;
        }

        public async Task<string> UploadAsync(
            string bucket,
            string objectName,
            Stream data,
            long size,
            string contentType,
            CancellationToken cancellationToken = default)
        {
            // ensure bucket exists
            var beArgs = new BucketExistsArgs().WithBucket(bucket);
            var exists = await _client.BucketExistsAsync(beArgs, cancellationToken);
            if (!exists)
            {
                await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), cancellationToken);
            }

            var putArgs = new PutObjectArgs()
                .WithBucket(bucket)
                .WithObject(objectName)
                .WithStreamData(data)
                .WithObjectSize(size)
                .WithContentType(string.IsNullOrWhiteSpace(contentType) ? MediaTypeNames.Application.Octet : contentType);

            await _client.PutObjectAsync(putArgs, cancellationToken);
            // Return the object path (bucket/object)
            return $"{bucket}/{objectName}";
        }
    }
}
